package cn.com.qiter.eduorder.controller;


import cn.com.qiter.common.Result;
import cn.com.qiter.common.ordervo.UcenterMemberOrder;
import cn.com.qiter.common.vo.ProjectModel;
import cn.com.qiter.common.vo.QrcodeModel;
import cn.com.qiter.eduorder.client.DictionaryClient;
import cn.com.qiter.eduorder.client.UcenterClient;
import cn.com.qiter.eduorder.entity.TrafficControl;
import cn.com.qiter.eduorder.entity.WorkVideo;
import cn.com.qiter.eduorder.entity.vo.TrafficQuery;
import cn.com.qiter.eduorder.entity.vo.TrafficVo;
import cn.com.qiter.eduorder.entity.vo.VideoQuery;
import cn.com.qiter.eduorder.entity.vo.VideoVo;
import cn.com.qiter.eduorder.service.TrafficControlService;
import cn.com.qiter.eduorder.service.WorkVideoService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 * 交通作业视频业务表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-04-19
 */
@Log4j2
@RestController
@RequestMapping("/eduorder/video")
public class WorkVideoController {

    @Autowired
    private WorkVideoService workVideoService;


    @Autowired
    private DictionaryClient dictionaryClient;

    @Autowired
    private UcenterClient ucenterClient;

    //1 查询讲师表所有数据
    //rest风格
    @ApiOperation(value = "所有防治列表")
    @GetMapping("findAll")
    public Result findAll() {
        //调用service的方法实现查询所有的操作
        List<WorkVideo> list = workVideoService.list(null);
        return Result.ok().data("rows",list);
    }

    //2 逻辑删除讲师的方法
    @ApiOperation(value = "逻辑删除防治")
    @DeleteMapping("remove/{id}")
    public Result remove(@ApiParam(name = "id", value = "ID", required = true)
                         @PathVariable String id) {
        boolean flag = workVideoService.removeById(id);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //3 分页查询讲师的方法
    //current 当前页
    //limit 每页记录数
    @GetMapping("page/{current}/{limit}")
    public Result page(@PathVariable long current,
                       @PathVariable long limit) {
        //创建page对象
        Page<WorkVideo> page = new Page<>(current,limit);
        //调用方法实现分页
        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
        workVideoService.page(page,null);
        long total = page.getTotal();//总记录数
        List<WorkVideo> records = page.getRecords(); //数据list集合
        return Result.ok().data("total",total).data("rows",records);
    }

    //4 条件查询带分页的方法
    @PostMapping("pageCondition/{current}/{limit}")
    public Result pageCondition(@PathVariable long current, @PathVariable long limit,
                                @RequestBody(required = false) VideoQuery query) {
        ObjectMapper mapper = new ObjectMapper();
        //创建page对象
        Page<WorkVideo> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<WorkVideo> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = query.getDeviceId();
        String begin = query.getBegin();
        String end = query.getEnd();
        String qrcode = query.getQrcode();
        String userId = query.getUserId();
        String projectId = query.getProjectId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }

        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        if(!StringUtils.isEmpty(qrcode)) {
            wrapper.eq("qrcode",qrcode);
        }
        //排序
        wrapper.orderByDesc("stime");

        //调用方法实现条件查询分页
        workVideoService.page(pageTeacher,wrapper);
        log.error(pageTeacher.getPages());
        log.error(pageTeacher.getSize());
        long pages = pageTeacher.getPages();
        long size = pageTeacher.getSize();
        log.error(pageTeacher.getCountId());
        log.error(pageTeacher.getMaxLimit());
        long total = pageTeacher.getTotal();//总记录数
        List<WorkVideo> records = pageTeacher.getRecords(); //数据list集合
        List<VideoVo> record = new ArrayList<>();
        for (WorkVideo pc :
                records) {
            VideoVo vo = new VideoVo();
            BeanUtil.copyProperties(pc,vo);
            Result qcode = ucenterClient.getByName(pc.getQrcode());
            UcenterMemberOrder ucenter = ucenterClient.getUserInfoOrder(pc.getUserId());
            LinkedHashMap lhm = (LinkedHashMap) qcode.getData().get("teacher");
            QrcodeModel qm = mapper.convertValue(lhm,QrcodeModel.class);
            vo.setQrcodeModel(qm);
            vo.setUcenterMemberModel(ucenter);
            Result  project = ucenterClient.getProjectById(pc.getProjectId());
            LinkedHashMap plhm = (LinkedHashMap) project.getData().get("teacher");
            ProjectModel pm = mapper.convertValue(plhm,ProjectModel.class);
            vo.setProjectModel(pm);
            record.add(vo);
        }
        return Result.ok().data("total",total).data("pages",pages).data("size",size).data("rows",record);
    }

    //添加讲师接口的方法
    @PostMapping("add")
    public Result add(@RequestBody WorkVideo wv) {
        String qrcode = wv.getQrcode();
        String qcode = StrUtil.subAfter(qrcode,"=",true);
        wv.setQrcode(qcode);
        String str = wv.getUserId();
        UcenterMemberOrder memberOrder = ucenterClient.getUserInfoOrder(str);
        wv.setProjectId(memberOrder.getProjectId());
        wv.setStime(DateTime.now());
        wv.setPositionError(String.valueOf(RandomUtil.randomInt(15)));
        boolean save = workVideoService.save(wv);
        if(save) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //根据讲师id进行查询
    @GetMapping("getDictByName/{name}")
    public Result getDictByName(@PathVariable String name) {
        Result result = dictionaryClient.getByName(name);
        return Result.ok().data("dict",result);
    }
    //根据讲师id进行查询
    @GetMapping("get/{id}")
    public Result get(@PathVariable String id) {
        WorkVideo video = workVideoService.getById(id);
        return Result.ok().data("video",video);
    }

    /**
     * 可以进行多次扫码施工
     * @param qrcode
     * @return
     */
    @GetMapping("getByQrcode/{qrcode}")
    public Result getByQrcode(@PathVariable String qrcode) {
        QueryWrapper<WorkVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("qrcode",qrcode);
        List<WorkVideo> eduTeacher = workVideoService.list(wrapper);
        return Result.ok().data("video",eduTeacher);
    }
    //讲师修改功能
    @PostMapping("update")
    public Result update(@RequestBody WorkVideo eduTeacher) {
        boolean flag = workVideoService.updateById(eduTeacher);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    /**
     *  统计某天的数据量
     * @param day
     * @return
     */
    @GetMapping("countDay/{day}")
    public Result countDay(@PathVariable String day) {
        Integer count = workVideoService.countDay(day);
        return Result.ok().data("countDay",count);
    }

    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
//    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}")
    public Result countDay(@PathVariable String day , @PathVariable String projectId) {
        Integer count = workVideoService.countDayByProjectId(day,projectId);
        return Result.ok().data("countDay",count);
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
//    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}/{memberId}")
    public Result countDay(@PathVariable String day,@PathVariable String projectId,@PathVariable String memberId) {
        Integer count = workVideoService.countDayByProjectIdAndMemberId(day,projectId,memberId);
        return Result.ok().data("countDay",count);
    }

}

